
<!DOCTYPE html>
<html lang="zh-CN" class="loading">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>网络部分知识开发和应用 - 浪子之心</title>
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="google" content="notranslate" />
    <meta name="keywords" content="Blog,"> 
    <meta name="description" content="MrChen Bolg,网络模型socket结构
iocp（Input&amp;#x2F;output completion port）SocketAPI输入&amp;#x2F;输出完成端口，常常使用在windows系统中，采用异步的方式,"> 
    <meta name="author" content="Jack Chen"> 
    <link rel="alternative" href="atom.xml" title="浪子之心" type="application/atom+xml"> 
    <link rel="icon" href="/blog/img/favicon.png"> 
    
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css">

    
<link rel="stylesheet" href="/blog/css/diaspora.css">

<meta name="generator" content="Hexo 5.4.1"><link rel="stylesheet" href="/blog/css/prism.css" type="text/css"></head>

<body class="loading">
    <span id="config-title" style="display:none">浪子之心</span>
    <div id="loader"></div>
    <div id="single">
    <div id="top" style="display: block;">
    <div class="bar" style="width: 0;"></div>
    <a class="iconfont icon-home image-icon" href="javascript:;" data-url="https://mrchenlearnspace.github.io/blog"></a>
    <div title="播放/暂停" class="iconfont icon-play"></div>
    <h3 class="subtitle">网络部分知识开发和应用</h3>
    <div class="social">
        <div>
            <div class="share">
                <a title="获取二维码" class="iconfont icon-scan" href="javascript:;"></a>
            </div>
            <div id="qr"></div>
        </div>
    </div>
    <div class="scrollbar"></div>
</div>

    <div class="section">
        <div class="article">
    <div class='main'>
        <h1 class="title">网络部分知识开发和应用</h1>
        <div class="stuff">
            <span>十月 15, 2022</span>
            
  <ul class="post-tags-list" itemprop="keywords"><li class="post-tags-list-item"><a class="post-tags-list-link" href="/blog/tags/%E7%BD%91%E7%BB%9C/" rel="tag">网络</a></li></ul>


        </div>
        <div class="content markdown">
            <h1 id="网络模型"><a href="#网络模型" class="headerlink" title="网络模型"></a>网络模型</h1><p>socket结构<br><img src="https://img-blog.csdnimg.cn/92c574ee864f4bc685e8ec5213c70e1c.png" alt="在这里插入图片描述"></p>
<h2 id="iocp（Input-x2F-output-completion-port）"><a href="#iocp（Input-x2F-output-completion-port）" class="headerlink" title="iocp（Input&#x2F;output completion port）"></a>iocp（Input&#x2F;output completion port）</h2><p><a target="_blank" rel="noopener" href="https://learn.microsoft.com/zh-cn/dotnet/api/system.net.sockets?view=net-6.0">SocketAPI</a><br>输入&#x2F;输出完成端口，常常使用在windows系统中，采用异步的方式对每个socket进行监听和接收。</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br></pre></td><td class="code"><pre><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">Start</span>(<span class="params"><span class="built_in">string</span> host, <span class="built_in">int</span> port</span>)</span> &#123;</span><br><span class="line"></span><br><span class="line">    timer.Elapsed += <span class="keyword">new</span> System.Timers.ElapsedEventHandler(HandleMainTimer);</span><br><span class="line">    timer.AutoReset = <span class="literal">false</span>;</span><br><span class="line">    timer.Enabled = <span class="literal">true</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    conns = <span class="keyword">new</span> Conn[maxConn];</span><br><span class="line">    <span class="keyword">for</span> (<span class="built_in">int</span> i = <span class="number">0</span>; i &lt; maxConn; i++) &#123;</span><br><span class="line">        conns[i] = <span class="keyword">new</span> Conn();</span><br><span class="line">    &#125;</span><br><span class="line">    listenfd = <span class="keyword">new</span> Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);</span><br><span class="line">    IPAddress ipAdr = IPAddress.Parse(host);</span><br><span class="line">    IPEndPoint ipEp = <span class="keyword">new</span> IPEndPoint(ipAdr, port);</span><br><span class="line">    listenfd.Bind(ipEp);</span><br><span class="line">    listenfd.Listen(maxConn);</span><br><span class="line">    listenfd.BeginAccept(AcceptCb, <span class="literal">null</span>);</span><br><span class="line">    Console.WriteLine (<span class="string">&quot;[服务器]启动成功&quot;</span>);</span><br><span class="line">&#125;</span><br><span class="line"> <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">AcceptCb</span>(<span class="params">IAsyncResult ar</span>)</span> &#123;</span><br><span class="line">    Socket socket = listenfd.EndAccept(ar);</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="comment">//接收客户端</span></span><br><span class="line">        <span class="built_in">int</span> index = NewIndex();</span><br><span class="line">        <span class="keyword">if</span> (index &lt; <span class="number">0</span>) &#123;</span><br><span class="line">            socket.Close();</span><br><span class="line">            Console.WriteLine(<span class="string">&quot;[警告]连接已满&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> &#123;</span><br><span class="line">            Conn conn = conns[index];</span><br><span class="line">            conn.Init(socket);</span><br><span class="line">            <span class="built_in">string</span> host = conn.GetAdress();</span><br><span class="line">            Console.WriteLine(<span class="string">&quot;客户端连接:[&quot;</span> + host + <span class="string">&quot;] conn池ID:&quot;</span> + index);</span><br><span class="line">            conn.socket.BeginReceive(conn.readBuff, conn.buffCount, conn.BuffRemain(), SocketFlags.None, ReciveCb, conn);<span class="comment">//接收的同时调用ReciveCb回调函数</span></span><br><span class="line">        &#125;</span><br><span class="line">        listenfd.BeginAccept(AcceptCb, <span class="literal">null</span>);<span class="comment">//再次调用AcceprCb回调函数</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">        Console.WriteLine(<span class="string">&quot;AccpetCb 失败:&quot;</span> + e.Message);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">private</span>  <span class="keyword">void</span> <span class="title">ReciveCb</span>(<span class="params">IAsyncResult ar</span>)</span> &#123;</span><br><span class="line">    Conn conn = (Conn)ar.AsyncState;<span class="comment">//这个AsyncState就是上面那个BeginRecive函数里面最后一个参数</span></span><br><span class="line">    <span class="keyword">lock</span> (conn) &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="built_in">int</span> count = conn.socket.EndReceive(ar);<span class="comment">//返回接收的字节数</span></span><br><span class="line">                                                   <span class="comment">//没有信息就关闭</span></span><br><span class="line">            <span class="keyword">if</span> (count &lt;= <span class="number">0</span>) &#123;</span><br><span class="line">                Console.WriteLine(<span class="string">&quot;收到[&quot;</span> + conn.GetAdress() + <span class="string">&quot;] 断开连接&quot;</span>);</span><br><span class="line">                conn.Close();</span><br><span class="line">                <span class="keyword">return</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            conn.buffCount += count;</span><br><span class="line">            ProcessData(conn);</span><br><span class="line">            </span><br><span class="line">            <span class="comment">//继续接收</span></span><br><span class="line">            conn.socket.BeginReceive(conn.readBuff, conn.buffCount, conn.BuffRemain(), SocketFlags.None, ReciveCb, conn);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            Console.WriteLine(<span class="string">&quot;Recive失败&quot;</span> + e.Message);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h3 id="缺点"><a href="#缺点" class="headerlink" title="缺点"></a>缺点</h3><p>异步操作可能会产生死锁等线程问题</p>
<h2 id="状态检测Poll"><a href="#状态检测Poll" class="headerlink" title="状态检测Poll"></a>状态检测Poll</h2><p><a target="_blank" rel="noopener" href="https://learn.microsoft.com/zh-cn/dotnet/api/system.net.sockets.socket.poll?view=net-6.0#system-net-sockets-socket-poll%28system-int32-system-net-sockets-selectmode%29">Poll函数</a><br>采用同步循环的方式进行监听</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span>(socket有可读数据）</span><br><span class="line">socket.Receive() </span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span>(socket缓冲区可写）</span><br><span class="line">socket. Send () </span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span>(socket发生程序）</span><br><span class="line">错误处理</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>服务器实现</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">初始化listenfd</span><br><span class="line">初始化clients列表</span><br><span class="line"><span class="keyword">while</span>(<span class="literal">true</span>)&#123; </span><br><span class="line">  <span class="keyword">if</span>(listenfd可读） Accept; </span><br><span class="line">  <span class="keyword">for</span>(遍历clien七s列表） ｛ </span><br><span class="line">    <span class="keyword">if</span>（这个客户端可读） 消息处理;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>具体实现</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> Socket listenfd;</span><br><span class="line"><span class="comment">//客户端Socket及状态信息</span></span><br><span class="line"><span class="keyword">static</span> Dictionary&lt;Socket, ClientState&gt; clients = <span class="keyword">new</span> Dictionary&lt;Socket, ClientState&gt;();</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">Main</span>(<span class="params"><span class="built_in">string</span>[] args</span>)</span> &#123;</span><br><span class="line">  <span class="comment">//Socket </span></span><br><span class="line">  listenfd = <span class="keyword">new</span> Socket(AddressFamily.InterNetwork,</span><br><span class="line">  SocketType.Stream, ProtocolType.Tcp);</span><br><span class="line">  <span class="comment">//Bind </span></span><br><span class="line">  IPAddress ipAdr = IPAddress.Parse(<span class="string">&quot;l27.0.0.l&quot;</span>);</span><br><span class="line">  IPEndPoint ipEp = <span class="keyword">new</span> IPEndPoint(ipAdr, <span class="number">8888</span>);</span><br><span class="line">  listenfd.Bind(ipEp);</span><br><span class="line">  <span class="comment">//Listen </span></span><br><span class="line">  listenfd.Listen(<span class="number">0</span>);</span><br><span class="line">  Console.WriteLine(<span class="string">&quot; （服务器］启动成功&quot;</span>);</span><br><span class="line">  <span class="comment">//主循环</span></span><br><span class="line">  <span class="keyword">while</span> (<span class="literal">true</span>) &#123;</span><br><span class="line">    <span class="comment">//检查listenfd</span></span><br><span class="line">    <span class="keyword">if</span> (listenfd.Poll(<span class="number">0</span>, SelectMode.SelectRead)) &#123;</span><br><span class="line">      ReadListenfd(listenfd);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//检查clientfd</span></span><br><span class="line">    <span class="keyword">foreach</span> (ClientState s <span class="keyword">in</span> clients.Values) &#123;</span><br><span class="line">      Socket clientfd = s.socket;</span><br><span class="line">      <span class="keyword">if</span> (clientfd.Poll(<span class="number">0</span>, SelectMode.SelectRead)) &#123;</span><br><span class="line">        <span class="keyword">if</span> (!ReadClientfd(clientfd))</span><br><span class="line">          <span class="keyword">break</span>;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">//防止CPU占用过高</span></span><br><span class="line">      System.Threading.Thread.Sleep(<span class="number">1</span>);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">ReadListenfd</span>(<span class="params">Socket listenfd</span>)</span> &#123;</span><br><span class="line">  Console.WriteLine(<span class="string">&quot;Accept&quot;</span>);</span><br><span class="line">  Socket clientfd = listenfd.Accept();</span><br><span class="line">  ClientState state = <span class="keyword">new</span> ClientState();</span><br><span class="line">  state.socket = clientfd;</span><br><span class="line">  clients.Add(clientfd, state);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//读取 Clientfd</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="built_in">bool</span> <span class="title">ReadClientfd</span>(<span class="params">Socket clientfd</span>)</span> &#123;</span><br><span class="line">  ClientState state = clients[clientfd];</span><br><span class="line">  <span class="comment">//接收</span></span><br><span class="line">  <span class="built_in">int</span> count = <span class="number">0</span>;</span><br><span class="line">  <span class="keyword">try</span> &#123;</span><br><span class="line">    count = clientfd.Receive(state.readBuff);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">catch</span> (SocketException ex) &#123;</span><br><span class="line">    clientfd.Close();</span><br><span class="line">    clients.Remove(clientfd);</span><br><span class="line">    Console.WriteLine(<span class="string">&quot;Receive SocketExcep七ion &quot;</span> + ex.ToString());</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  <span class="comment">//客户端关闭</span></span><br><span class="line">  <span class="keyword">if</span> (count == <span class="number">0</span>) &#123;</span><br><span class="line">    clientfd.Close();</span><br><span class="line">    clients.Remove(clientfd);</span><br><span class="line">    Console.WriteLine(<span class="string">&quot;Socket Close&quot;</span>);</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">//广播</span></span><br><span class="line"></span><br><span class="line">  <span class="built_in">string</span> recvStr = System.Text.Encoding.Default.GetString(state.readBuff, <span class="number">0</span>, count);</span><br><span class="line">  Console.WriteLine(<span class="string">&quot;Receive&quot;</span> + recvStr);</span><br><span class="line">  <span class="built_in">string</span> sendStr = clientfd.RemoteEndPoint.ToString() + <span class="string">&quot;:&quot;</span> + recvStr;</span><br><span class="line">  <span class="built_in">byte</span>[] sendBytes = System.Text.Encoding.Default.GetBytes(sendStr);</span><br><span class="line">  <span class="keyword">foreach</span> (ClientState cs <span class="keyword">in</span> clients.Values) &#123;</span><br><span class="line">    cs.socket.Send(sendBytes);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h3 id="注意"><a href="#注意" class="headerlink" title="注意"></a>注意</h3><ol>
<li>在主循环最后涸用了System.Threading. Thread.Sleep(I)， 让程序挂起1毫秒， 这样做的目的是避免死循环， 让 CPU 有个短暂的喘息时间。</li>
<li>ReadClientfd会返回true或false, 返回false表示该客户端断开（收到长度为<br>0的数据）。 由于客户端断开后，ReadClientfd会删除clients列表中对应的客户端信息， 导致clients列表改变， 而ReadClientfd又是在foreach (ClientState s in clients.Values)的循环中被调用的， clients列表变化会导致遍历失败， 因此程序在检测到客户端关闭后将退出foreach循环。</li>
<li>是将 Poll 的超时时间设置为 0, 程序不会有任何等待。 如果设置较长的超时时间，服务端将无法及时处理多个客户端同时连接的情况。 当然 ， 这样设置也会导致程序的<strong>CPU占用率很高</strong>。<h3 id="缺点-1"><a href="#缺点-1" class="headerlink" title="缺点"></a>缺点</h3>cpu占用率过高<h2 id="多路复用Select"><a href="#多路复用Select" class="headerlink" title="多路复用Select"></a>多路复用Select</h2><a target="_blank" rel="noopener" href="https://learn.microsoft.com/zh-cn/dotnet/api/system.net.sockets.socket.select?view=net-6.0#system-net-sockets-socket-select%28system-collections-ilist-system-collections-ilist-system-collections-ilist-system-int32%29">Select函数</a><br>同时检测多个Socket的状态 在设性要监听的Socket列表后 ， 如果有一个（或多个）Socket可读 （或可写 ， 或发生错误信息）， 那就返同这些可读的 Socket, 如果没有可读的 ， 那就阻塞</li>
</ol>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> Socket listenfd;</span><br><span class="line"><span class="comment">//客户端 Socket及状态信息</span></span><br><span class="line"><span class="keyword">static</span> Dictionary&lt;Socket, ClientState&gt; clients = <span class="keyword">new</span> Dictionary&lt;Socket, <span class="function">Client</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">Main</span>(<span class="params"><span class="built_in">string</span>[] args</span>)</span> &#123;</span><br><span class="line">    <span class="comment">//Socket </span></span><br><span class="line">    listenfd = <span class="keyword">new</span> Socket(AddressFamily.InterNetwork, SocketType.Stream, Proto</span><br><span class="line">    <span class="comment">//Bind </span></span><br><span class="line">    IPAddress ipAdr = IPAddress.Parse(<span class="string">&quot;l27.0.0.l&quot;</span>);</span><br><span class="line">    IPEndPoint ipEp = <span class="keyword">new</span> IPEndPoint(ipAdr, <span class="number">8888</span>);</span><br><span class="line">    listenfd.Bind(ipEp);</span><br><span class="line">    <span class="comment">//Listen </span></span><br><span class="line">    listenfd.Listen(<span class="number">0</span>);</span><br><span class="line">    Console.WriteLine(<span class="string">&quot;［服务器］启动成功&quot;</span>);</span><br><span class="line">    <span class="comment">//checkRead </span></span><br><span class="line">    List&lt;Socket&gt; checkRead = <span class="keyword">new</span> List&lt;Socket&gt;();</span><br><span class="line">    <span class="comment">//主循环</span></span><br><span class="line">    <span class="keyword">while</span> (<span class="literal">true</span>) &#123;</span><br><span class="line">        <span class="comment">//填充 checkRead列表</span></span><br><span class="line">        checkRead.Clear();</span><br><span class="line">        checkRead.Add(listenfd);</span><br><span class="line">        <span class="keyword">foreach</span> (ClientState s <span class="keyword">in</span> clients.Values) &#123;</span><br><span class="line">            checkRead.Add(s.socket);</span><br><span class="line">            <span class="comment">//select</span></span><br><span class="line">            Socket.Select(checkRead, <span class="literal">null</span>, <span class="literal">null</span>, <span class="number">1000</span>);</span><br><span class="line">            <span class="comment">//检查可读对象</span></span><br><span class="line">            <span class="keyword">foreach</span> (Socket s <span class="keyword">in</span> checkRead) &#123;</span><br><span class="line">                <span class="keyword">if</span> (s == listenfd) &#123;</span><br><span class="line">                      ReadListenfd(s); </span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">else</span> &#123;</span><br><span class="line">                      ReadClientfd(s);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h3 id="过程"><a href="#过程" class="headerlink" title="过程"></a>过程</h3><p>服务端使用主循环结构 while(true){…} ， 不断地调用 Select 检测 Socket 状态， 其步骤如下：</p>
<ol>
<li>将监听 Socket (listenfd) 和客户端 Socket （遍历 clients 列表）添加到待检测 Socket可读状态的列表 checkList 中。</li>
<li>调用 Select, 程序中设置超时时间为 1 秒， 若 l 秒内没有任何可读信息， Select 方法将 checkList 列表变成空列表， 然后返回。</li>
<li>对 Select 处理后的每个 Socket 做处理， 如果监听 Socket (listenfd) 可读， 说明有客户端连接， 需凋用 Accept。 如果客户端 Socket 可读， 说明客户端发送了消息（或关闭）， 将消息广播给所有客户端<h3 id="适用空间"><a href="#适用空间" class="headerlink" title="适用空间"></a>适用空间</h3>由于程序在 Update 中不停地检测数据， 性能较差。 商业上为了做到性能上的极致， 大多使用异步（或使用多线程模拟异步程序）。<h1 id="解决粘包问题的方法"><a href="#解决粘包问题的方法" class="headerlink" title="解决粘包问题的方法"></a>解决粘包问题的方法</h1><h2 id="长度信息法"><a href="#长度信息法" class="headerlink" title="长度信息法"></a>长度信息法</h2>长度信息法是指在每个数据包前面加上长度信息。 每次接收到数据后 ， 先读取表示长度的字节 ， 如果缓冲区的数据长度大千要取的字节数， 则取出相应的字节 ， 否则等待下一次数据接收。<br><img src="https://img-blog.csdnimg.cn/3654997df07e467eb8c74b4fc6d3137f.png" alt="在这里插入图片描述"></li>
</ol>
<h2 id="固定长度法"><a href="#固定长度法" class="headerlink" title="固定长度法"></a>固定长度法</h2><p>固定一个长度发送消息时多余部分用其他字符填充</p>
<h2 id="结束符号法"><a href="#结束符号法" class="headerlink" title="结束符号法"></a>结束符号法</h2><p>在消息最后加一个特殊字符</p>
<h1 id="大端小端问题"><a href="#大端小端问题" class="headerlink" title="大端小端问题"></a>大端小端问题</h1><p>来自于平台的不同导致高地址和低地址的顺序不同<br><img src="https://img-blog.csdnimg.cn/ba86c22a0ead49cc82ccd64049535145.png" alt="在这里插入图片描述"></p>
<p>相反则是大端模式，常用的X86结构是小端模式 ， 很多的ARM、 DSP都为小端模式， 但KEIL CS I则为大端模式 ， 有些 ARM 处理器还可以由硬件来选择是大端模式还是小端模式。 也就是说市面上的手机有些采用大端模式， 有些采用小端模式</p>
<h2 id="解决方案"><a href="#解决方案" class="headerlink" title="解决方案"></a>解决方案</h2><p>采用Reverse统一顺序。</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span>(!BitConverter.IsLittleEndian)&#123; </span><br><span class="line">  Debug.Log(<span class="string">&quot;[Send] Reverse lenBytes&quot;</span>); </span><br><span class="line">  lenBytes.Reverse();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//int16时</span></span><br><span class="line">Int16 bodyLength = (<span class="built_in">short</span>)((readBuff[<span class="number">1</span>] &lt;&lt;<span class="number">8</span>) | readBuff[O]);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//int32时</span></span><br><span class="line">Int32 bodyLength =readBuff[O]; </span><br><span class="line"><span class="keyword">for</span>(<span class="built_in">int</span> i=<span class="number">1</span>;i&lt;<span class="number">4</span>;i++)</span><br><span class="line">&#123;</span><br><span class="line">  bodyLength = (readBuff[i]&lt;&lt;(<span class="number">8</span>*i))|bodyLength ;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h1 id="BytesArray"><a href="#BytesArray" class="headerlink" title="BytesArray"></a>BytesArray</h1><p>用来储存发送和接收的数据结构。</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">using</span> System;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">ByteArray</span>  &#123;</span><br><span class="line">  <span class="comment">//默认大小</span></span><br><span class="line">  <span class="keyword">const</span> <span class="built_in">int</span> DEFAULT_SIZE = <span class="number">1024</span>;</span><br><span class="line">  <span class="comment">//初始大小</span></span><br><span class="line">  <span class="built_in">int</span> initSize = <span class="number">0</span>;</span><br><span class="line">  <span class="comment">//缓冲区</span></span><br><span class="line">  <span class="keyword">public</span> <span class="built_in">byte</span>[] bytes;</span><br><span class="line">  <span class="comment">//读写位置</span></span><br><span class="line">  <span class="keyword">public</span> <span class="built_in">int</span> readIdx = <span class="number">0</span>;</span><br><span class="line">  <span class="keyword">public</span> <span class="built_in">int</span> writeIdx = <span class="number">0</span>;</span><br><span class="line">  <span class="comment">//容量</span></span><br><span class="line">  <span class="keyword">private</span> <span class="built_in">int</span> capacity = <span class="number">0</span>;</span><br><span class="line">  <span class="comment">//剩余空间</span></span><br><span class="line">  <span class="keyword">public</span> <span class="built_in">int</span> remain &#123; <span class="keyword">get</span> &#123; <span class="keyword">return</span> capacity-writeIdx; &#125;&#125;</span><br><span class="line">  <span class="comment">//数据长度</span></span><br><span class="line">  <span class="keyword">public</span> <span class="built_in">int</span> length &#123; <span class="keyword">get</span> &#123; <span class="keyword">return</span> writeIdx-readIdx; &#125;&#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">//构造函数</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="title">ByteArray</span>(<span class="params"><span class="built_in">int</span> size = DEFAULT_SIZE</span>)</span>&#123;</span><br><span class="line">    bytes = <span class="keyword">new</span> <span class="built_in">byte</span>[size];</span><br><span class="line">    capacity = size;</span><br><span class="line">    initSize = size;</span><br><span class="line">    readIdx = <span class="number">0</span>;</span><br><span class="line">    writeIdx = <span class="number">0</span>;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">//构造函数</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="title">ByteArray</span>(<span class="params"><span class="built_in">byte</span>[] defaultBytes</span>)</span>&#123;</span><br><span class="line">    bytes = defaultBytes;</span><br><span class="line">    capacity = defaultBytes.Length;</span><br><span class="line">    initSize = defaultBytes.Length;</span><br><span class="line">    readIdx = <span class="number">0</span>;</span><br><span class="line">    writeIdx = defaultBytes.Length;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">//重设尺寸</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">ReSize</span>(<span class="params"><span class="built_in">int</span> size</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(size &lt; length) <span class="keyword">return</span>;</span><br><span class="line">    <span class="keyword">if</span>(size &lt; initSize) <span class="keyword">return</span>;</span><br><span class="line">    <span class="built_in">int</span> n = <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">while</span>(n&lt;size) n*=<span class="number">2</span>;</span><br><span class="line">    capacity = n;</span><br><span class="line">    <span class="built_in">byte</span>[] newBytes = <span class="keyword">new</span> <span class="built_in">byte</span>[capacity];</span><br><span class="line">    Array.Copy(bytes, readIdx, newBytes, <span class="number">0</span>, writeIdx-readIdx);</span><br><span class="line">    bytes = newBytes;</span><br><span class="line">    writeIdx = length;</span><br><span class="line">    readIdx = <span class="number">0</span>;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">//写入数据</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="built_in">int</span> <span class="title">Write</span>(<span class="params"><span class="built_in">byte</span>[] bs, <span class="built_in">int</span> offset, <span class="built_in">int</span> count</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(remain &lt; count)&#123;</span><br><span class="line">      ReSize(length + count);</span><br><span class="line">    &#125;</span><br><span class="line">    Array.Copy(bs, offset, bytes, writeIdx, count);</span><br><span class="line">    writeIdx+=count;</span><br><span class="line">    <span class="keyword">return</span> count;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">//读取数据</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="built_in">int</span> <span class="title">Read</span>(<span class="params"><span class="built_in">byte</span>[] bs, <span class="built_in">int</span> offset, <span class="built_in">int</span> count</span>)</span>&#123;</span><br><span class="line">    count = Math.Min(count, length);</span><br><span class="line">    Array.Copy(bytes, <span class="number">0</span>, bs, offset, count);</span><br><span class="line">    readIdx+=count;</span><br><span class="line">    CheckAndMoveBytes();</span><br><span class="line">    <span class="keyword">return</span> count;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">//检查并移动数据</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">CheckAndMoveBytes</span>()</span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(length &lt; <span class="number">8</span>)&#123;</span><br><span class="line">      MoveBytes();</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">//移动数据</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">MoveBytes</span>()</span>&#123;</span><br><span class="line">    Array.Copy(bytes, readIdx, bytes, <span class="number">0</span>, length);</span><br><span class="line">    writeIdx = length;</span><br><span class="line">    readIdx = <span class="number">0</span>;</span><br><span class="line">  &#125; </span><br><span class="line"></span><br><span class="line">  <span class="comment">//读取Int16</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> Int16 <span class="title">ReadInt16</span>()</span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(length &lt; <span class="number">2</span>) <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    Int16 ret = BitConverter.ToInt16(bytes, readIdx);</span><br><span class="line">    readIdx += <span class="number">2</span>;</span><br><span class="line">    CheckAndMoveBytes();</span><br><span class="line">    <span class="keyword">return</span> ret;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">//读取Int32</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> Int32 <span class="title">ReadInt32</span>()</span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(length &lt; <span class="number">4</span>) <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    Int32 ret = BitConverter.ToInt32(bytes, readIdx);</span><br><span class="line">    readIdx += <span class="number">4</span>;</span><br><span class="line">    CheckAndMoveBytes();</span><br><span class="line">    <span class="keyword">return</span> ret;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  <span class="comment">//打印缓冲区</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">override</span> <span class="built_in">string</span> <span class="title">ToString</span>()</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> BitConverter.ToString(bytes, readIdx, length);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">//打印调试信息</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="built_in">string</span> <span class="title">Debug</span>()</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">string</span>.Format(<span class="string">&quot;readIdx(&#123;0&#125;) writeIdx(&#123;1&#125;) bytes(&#123;2&#125;)&quot;</span>,</span><br><span class="line">      readIdx,</span><br><span class="line">      writeIdx,</span><br><span class="line">      BitConverter.ToString(bytes, <span class="number">0</span>, capacity)</span><br><span class="line">    );</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h1 id="异步处理"><a href="#异步处理" class="headerlink" title="异步处理"></a>异步处理</h1><p>参数如下<br>这是客户端部分，当具体到服务器应该去除静态</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//定义套接字</span></span><br><span class="line">  <span class="keyword">static</span> Socket socket;</span><br><span class="line">  <span class="comment">//接收缓冲区</span></span><br><span class="line">  <span class="keyword">static</span> ByteArray readBuff;</span><br><span class="line">  <span class="comment">//写入队列</span></span><br><span class="line">  <span class="keyword">static</span> Queue&lt;ByteArray&gt; writeQueue;</span><br><span class="line">  <span class="comment">//是否正在连接</span></span><br><span class="line">  <span class="keyword">static</span> <span class="built_in">bool</span> isConnecting = <span class="literal">false</span>;</span><br><span class="line">  <span class="comment">//是否正在关闭</span></span><br><span class="line">  <span class="keyword">static</span> <span class="built_in">bool</span> isClosing = <span class="literal">false</span>;</span><br><span class="line">  <span class="comment">//消息列表</span></span><br><span class="line">  <span class="keyword">static</span> List&lt;MsgBase&gt; msgList = <span class="keyword">new</span> List&lt;MsgBase&gt;();</span><br><span class="line">  <span class="comment">//消息列表长度</span></span><br><span class="line">  <span class="keyword">static</span> <span class="built_in">int</span> msgCount = <span class="number">0</span>;</span><br><span class="line">  <span class="comment">//每一次Update处理的消息量</span></span><br><span class="line">  <span class="keyword">readonly</span> <span class="keyword">static</span> <span class="built_in">int</span> MAX_MESSAGE_FIRE = <span class="number">10</span>;</span><br><span class="line">  <span class="comment">//是否启用心跳</span></span><br><span class="line">  <span class="keyword">public</span> <span class="keyword">static</span> <span class="built_in">bool</span> isUsePing = <span class="literal">true</span>;</span><br><span class="line">  <span class="comment">//心跳间隔时间</span></span><br><span class="line">  <span class="keyword">public</span> <span class="keyword">static</span> <span class="built_in">int</span> pingInterval = <span class="number">30</span>;</span><br><span class="line">  <span class="comment">//上一次发送PING的时间</span></span><br><span class="line">  <span class="keyword">static</span> <span class="built_in">float</span> lastPingTime = <span class="number">0</span>;</span><br><span class="line">  <span class="comment">//上一次收到PONG的时间</span></span><br><span class="line">  <span class="keyword">static</span> <span class="built_in">float</span> lastPongTime = <span class="number">0</span>;</span><br></pre></td></tr></table></figure>

<h2 id="异步连接"><a href="#异步连接" class="headerlink" title="异步连接"></a>异步连接</h2><p>引用致Unity网络游戏实战第二版</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//连接</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">Connect</span>(<span class="params"><span class="built_in">string</span> ip, <span class="built_in">int</span> port</span>)</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="comment">//状态判断</span></span><br><span class="line">  <span class="keyword">if</span>(socket!=<span class="literal">null</span> &amp;&amp; socket.Connected)&#123;</span><br><span class="line">    Debug.Log(<span class="string">&quot;Connect fail, already connected!&quot;</span>);</span><br><span class="line">    <span class="keyword">return</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">if</span>(isConnecting)&#123;</span><br><span class="line">    Debug.Log(<span class="string">&quot;Connect fail, isConnecting&quot;</span>);</span><br><span class="line">    <span class="keyword">return</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">//初始化成员</span></span><br><span class="line">  InitState();</span><br><span class="line">  <span class="comment">//参数设置</span></span><br><span class="line">  socket.NoDelay = <span class="literal">true</span>;</span><br><span class="line">  <span class="comment">//Connect</span></span><br><span class="line">  isConnecting = <span class="literal">true</span>;</span><br><span class="line">  socket.BeginConnect(ip, port, ConnectCallback, socket);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//初始化状态</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">InitState</span>()</span>&#123;</span><br><span class="line">  <span class="comment">//Socket</span></span><br><span class="line">  socket = <span class="keyword">new</span> Socket(AddressFamily.InterNetwork,</span><br><span class="line">    SocketType.Stream, ProtocolType.Tcp);</span><br><span class="line">  <span class="comment">//接收缓冲区</span></span><br><span class="line">  readBuff = <span class="keyword">new</span> ByteArray();</span><br><span class="line">  <span class="comment">//写入队列</span></span><br><span class="line">  writeQueue = <span class="keyword">new</span> Queue&lt;ByteArray&gt;();</span><br><span class="line">  <span class="comment">//是否正在连接</span></span><br><span class="line">  isConnecting = <span class="literal">false</span>;</span><br><span class="line">  <span class="comment">//是否正在关闭</span></span><br><span class="line">  isClosing = <span class="literal">false</span>;</span><br><span class="line">  <span class="comment">//消息列表</span></span><br><span class="line">  msgList = <span class="keyword">new</span> List&lt;MsgBase&gt;();</span><br><span class="line">  <span class="comment">//消息列表长度</span></span><br><span class="line">  msgCount = <span class="number">0</span>;</span><br><span class="line">  <span class="comment">//上一次发送PING的时间</span></span><br><span class="line">  lastPingTime = Time.time;</span><br><span class="line">  <span class="comment">//上一次收到PONG的时间</span></span><br><span class="line">  lastPongTime = Time.time;</span><br><span class="line">  <span class="comment">//监听PONG协议</span></span><br><span class="line">  <span class="keyword">if</span>(!msgListeners.ContainsKey(<span class="string">&quot;MsgPong&quot;</span>))&#123;</span><br><span class="line">    AddMsgListener(<span class="string">&quot;MsgPong&quot;</span>, OnMsgPong);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//Connect回调</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">ConnectCallback</span>(<span class="params">IAsyncResult ar</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">try</span>&#123;</span><br><span class="line">    Socket socket = (Socket) ar.AsyncState;</span><br><span class="line">    socket.EndConnect(ar);</span><br><span class="line">    Debug.Log(<span class="string">&quot;Socket Connect Succ &quot;</span>);</span><br><span class="line">    FireEvent(NetEvent.ConnectSucc,<span class="string">&quot;&quot;</span>);</span><br><span class="line">    isConnecting = <span class="literal">false</span>;</span><br><span class="line">    <span class="comment">//开始接收</span></span><br><span class="line">    socket.BeginReceive( readBuff.bytes, readBuff.writeIdx, readBuff.remain, <span class="number">0</span>, ReceiveCallback, socket);</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">catch</span> (SocketException ex)&#123;</span><br><span class="line">    Debug.Log(<span class="string">&quot;Socket Connect fail &quot;</span> + ex.ToString());</span><br><span class="line">    FireEvent(NetEvent.ConnectFail, ex.ToString());</span><br><span class="line">    isConnecting = <span class="literal">false</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125; </span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//关闭连接</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">Close</span>()</span>&#123;</span><br><span class="line">  <span class="comment">//状态判断</span></span><br><span class="line">  <span class="keyword">if</span>(socket==<span class="literal">null</span> || !socket.Connected)&#123;</span><br><span class="line">    <span class="keyword">return</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">if</span>(isConnecting)&#123;</span><br><span class="line">    <span class="keyword">return</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">//还有数据在发送</span></span><br><span class="line">  <span class="keyword">if</span>(writeQueue.Count &gt; <span class="number">0</span>)&#123;</span><br><span class="line">    isClosing = <span class="literal">true</span>;</span><br><span class="line">  &#125; </span><br><span class="line">  <span class="comment">//没有数据在发送</span></span><br><span class="line">  <span class="keyword">else</span>&#123;</span><br><span class="line">    socket.Close();</span><br><span class="line">    FireEvent(NetEvent.Close, <span class="string">&quot;&quot;</span>);</span><br><span class="line">  &#125; </span><br><span class="line">&#125; </span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h3 id="改进"><a href="#改进" class="headerlink" title="改进"></a>改进</h3><h2 id="异步发送"><a href="#异步发送" class="headerlink" title="异步发送"></a>异步发送</h2><p>引用致Unity网络游戏实战第二版</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//发送数据</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">Send</span>(<span class="params">MsgBase msg</span>)</span> &#123;</span><br><span class="line">  <span class="comment">//状态判断</span></span><br><span class="line">  <span class="keyword">if</span>(socket==<span class="literal">null</span> || !socket.Connected)&#123;</span><br><span class="line">    <span class="keyword">return</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">if</span>(isConnecting)&#123;</span><br><span class="line">    <span class="keyword">return</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">if</span>(isClosing)&#123;</span><br><span class="line">    <span class="keyword">return</span>;</span><br><span class="line">  &#125; </span><br><span class="line">  <span class="comment">//数据编码                 #带修改用linq改进</span></span><br><span class="line">  <span class="built_in">byte</span>[] nameBytes = MsgBase.EncodeName(msg);</span><br><span class="line">  <span class="built_in">byte</span>[] bodyBytes = MsgBase.Encode(msg);</span><br><span class="line">  <span class="built_in">int</span> len = nameBytes.Length + bodyBytes.Length;</span><br><span class="line">  <span class="built_in">byte</span>[] sendBytes = <span class="keyword">new</span> <span class="built_in">byte</span>[<span class="number">2</span>+len];</span><br><span class="line">  <span class="comment">//组装长度</span></span><br><span class="line">  sendBytes[<span class="number">0</span>] = (<span class="built_in">byte</span>)(len%<span class="number">256</span>);</span><br><span class="line">  sendBytes[<span class="number">1</span>] = (<span class="built_in">byte</span>)(len/<span class="number">256</span>);</span><br><span class="line">  <span class="comment">//组装名字</span></span><br><span class="line">  Array.Copy(nameBytes, <span class="number">0</span>, sendBytes, <span class="number">2</span>, nameBytes.Length);</span><br><span class="line">  <span class="comment">//组装消息体</span></span><br><span class="line">  Array.Copy(bodyBytes, <span class="number">0</span>, sendBytes, <span class="number">2</span>+nameBytes.Length, bodyBytes.Length);</span><br><span class="line">  <span class="comment">//写入队列                 /#带修改用linq改进</span></span><br><span class="line">  ByteArray ba = <span class="keyword">new</span> ByteArray(sendBytes);</span><br><span class="line">  <span class="built_in">int</span> count = <span class="number">0</span>;	<span class="comment">//writeQueue的长度</span></span><br><span class="line">  <span class="keyword">lock</span>(writeQueue)&#123;</span><br><span class="line">    writeQueue.Enqueue(ba);</span><br><span class="line">    count = writeQueue.Count;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">//send</span></span><br><span class="line">  <span class="keyword">if</span>(count == <span class="number">1</span>)&#123;</span><br><span class="line">    socket.BeginSend(sendBytes, <span class="number">0</span>, sendBytes.Length, </span><br><span class="line">      <span class="number">0</span>, SendCallback, socket);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//Send回调</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">SendCallback</span>(<span class="params">IAsyncResult ar</span>)</span>&#123;</span><br><span class="line"></span><br><span class="line">  <span class="comment">//获取state、EndSend的处理</span></span><br><span class="line">  Socket socket = (Socket) ar.AsyncState;</span><br><span class="line">  <span class="comment">//状态判断</span></span><br><span class="line">  <span class="keyword">if</span>(socket == <span class="literal">null</span> || !socket.Connected)&#123;</span><br><span class="line">    <span class="keyword">return</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">//EndSend</span></span><br><span class="line">  <span class="built_in">int</span> count = socket.EndSend(ar);</span><br><span class="line">  <span class="comment">//获取写入队列第一条数据            </span></span><br><span class="line">  ByteArray ba;</span><br><span class="line">  <span class="keyword">lock</span>(writeQueue)&#123;</span><br><span class="line">    ba = writeQueue.First();</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">//完整发送</span></span><br><span class="line">  ba.readIdx+=count;</span><br><span class="line">  <span class="keyword">if</span>(ba.length == <span class="number">0</span>)&#123;</span><br><span class="line">    <span class="keyword">lock</span>(writeQueue)&#123;</span><br><span class="line">      writeQueue.Dequeue();</span><br><span class="line">      ba = writeQueue.First();</span><br><span class="line">     &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">//继续发送</span></span><br><span class="line">  <span class="keyword">if</span>(ba != <span class="literal">null</span>)&#123;</span><br><span class="line">    socket.BeginSend(ba.bytes, ba.readIdx, ba.length, </span><br><span class="line">      <span class="number">0</span>, SendCallback, socket);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">//正在关闭</span></span><br><span class="line">  <span class="keyword">else</span> <span class="keyword">if</span>(isClosing) &#123;</span><br><span class="line">    socket.Close();</span><br><span class="line">  &#125; </span><br><span class="line">&#125; </span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h3 id="改进-1"><a href="#改进-1" class="headerlink" title="改进"></a>改进</h3><h2 id="异步接收"><a href="#异步接收" class="headerlink" title="异步接收"></a>异步接收</h2><p>引用致Unity网络游戏实战第二版</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//Receive回调</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">ReceiveCallback</span>(<span class="params">IAsyncResult ar</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">try</span> &#123;</span><br><span class="line">    Socket socket = (Socket) ar.AsyncState;</span><br><span class="line">    <span class="comment">//获取接收数据长度</span></span><br><span class="line">    <span class="built_in">int</span> count = socket.EndReceive(ar);</span><br><span class="line">    readBuff.writeIdx+=count;</span><br><span class="line">    <span class="comment">//处理二进制消息</span></span><br><span class="line">    OnReceiveData();</span><br><span class="line">    <span class="comment">//继续接收数据</span></span><br><span class="line">    <span class="keyword">if</span>(readBuff.remain &lt; <span class="number">8</span>)&#123;</span><br><span class="line">      readBuff.MoveBytes();</span><br><span class="line">      readBuff.ReSize(readBuff.length*<span class="number">2</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    socket.BeginReceive( readBuff.bytes, readBuff.writeIdx, readBuff.remain, <span class="number">0</span>, ReceiveCallback, socket);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">catch</span> (SocketException ex)&#123;</span><br><span class="line">    Debug.Log(<span class="string">&quot;Socket Receive fail&quot;</span> + ex.ToString());</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//数据处理</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">OnReceiveData</span>()</span>&#123;</span><br><span class="line">  <span class="comment">//消息长度</span></span><br><span class="line">  <span class="keyword">if</span>(readBuff.length &lt;= <span class="number">2</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">//获取消息体长度</span></span><br><span class="line">  <span class="built_in">int</span> readIdx = readBuff.readIdx;</span><br><span class="line">  <span class="built_in">byte</span>[] bytes =readBuff.bytes; </span><br><span class="line">  Int16 bodyLength = (Int16)((bytes[readIdx+<span class="number">1</span>] &lt;&lt; <span class="number">8</span> )| bytes[readIdx]);</span><br><span class="line">  <span class="keyword">if</span>(readBuff.length &lt; bodyLength)</span><br><span class="line">    <span class="keyword">return</span>;</span><br><span class="line">  readBuff.readIdx+=<span class="number">2</span>; </span><br><span class="line">  <span class="comment">//解析协议名</span></span><br><span class="line">  <span class="built_in">int</span> nameCount = <span class="number">0</span>;</span><br><span class="line">  <span class="built_in">string</span> protoName = MsgBase.DecodeName(readBuff.bytes, readBuff.readIdx, <span class="keyword">out</span> nameCount);</span><br><span class="line">  <span class="keyword">if</span>(protoName == <span class="string">&quot;&quot;</span>)&#123;</span><br><span class="line">    Debug.Log(<span class="string">&quot;OnReceiveData MsgBase.DecodeName fail&quot;</span>);</span><br><span class="line">    <span class="keyword">return</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  readBuff.readIdx += nameCount;</span><br><span class="line">  <span class="comment">//解析协议体</span></span><br><span class="line">  <span class="built_in">int</span> bodyCount = bodyLength - nameCount;</span><br><span class="line">  MsgBase msgBase = MsgBase.Decode(protoName, readBuff.bytes, readBuff.readIdx, bodyCount);</span><br><span class="line">  readBuff.readIdx += bodyCount;</span><br><span class="line">  readBuff.CheckAndMoveBytes();</span><br><span class="line">  <span class="comment">//添加到消息队列</span></span><br><span class="line">  <span class="keyword">lock</span>(msgList)&#123;</span><br><span class="line">    msgList.Add(msgBase);</span><br><span class="line">    msgCount++;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">//继续读取消息</span></span><br><span class="line">  <span class="keyword">if</span>(readBuff.length &gt; <span class="number">2</span>)&#123;</span><br><span class="line">    OnReceiveData();</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h3 id="改进-2"><a href="#改进-2" class="headerlink" title="改进"></a>改进</h3><h1 id="ProtoBuf"><a href="#ProtoBuf" class="headerlink" title="ProtoBuf"></a>ProtoBuf</h1><p>和json功能一样作为序列化的工具，当产生消耗更小，优化带宽。</p>
<h2 id="使用"><a href="#使用" class="headerlink" title="使用"></a>使用</h2><figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//将protobuf对象序列化为Byte数组  </span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="built_in">byte</span>[] <span class="title">Encode</span>(<span class="params">ProtoBuf.IExtensible msgBase</span>)</span>  </span><br><span class="line">  &#123;  </span><br><span class="line">    <span class="keyword">using</span> (<span class="keyword">var</span> memory = <span class="keyword">new</span> System.IO.MemoryStream())  </span><br><span class="line">    &#123;  </span><br><span class="line">      ProtoBuf.Serializer.Serialize(memory, msgBase); </span><br><span class="line">      <span class="keyword">return</span> memory.ToArray();  </span><br><span class="line">    &#125;  </span><br><span class="line">  &#125;  </span><br><span class="line"><span class="comment">//解码</span></span><br><span class="line">  <span class="keyword">public</span> <span class="keyword">static</span> ProtoBuf.<span class="function">IExtensible <span class="title">Decode</span>(<span class="params"><span class="built_in">string</span> protoName, <span class="built_in">byte</span>[] bytes, <span class="built_in">int</span> offset, <span class="built_in">int</span> count</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">using</span> (<span class="keyword">var</span> memory = <span class="keyword">new</span> System.IO.MemoryStream(bytes, offset, count))  </span><br><span class="line">    &#123;  </span><br><span class="line">      System.Type t = System.Type.GetType(protoName);</span><br><span class="line">      <span class="keyword">return</span> (ProtoBuf.IExtensible)ProtoBuf.Serializer.NonGeneric.Deserialize(t, memory);</span><br><span class="line">    &#125;  </span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>
<p>proto编写格式</p>
<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">message MsgMove&#123;</span><br><span class="line">  optional int32 x = <span class="number">1</span>;</span><br><span class="line">  optional int32 y = <span class="number">2</span>;</span><br><span class="line">  optional int32 z = <span class="number">3</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">message MsgAttack&#123;</span><br><span class="line">  optional <span class="built_in">string</span> desc = <span class="number">1</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h2 id="生成代码"><a href="#生成代码" class="headerlink" title="生成代码"></a>生成代码</h2><figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//------------------------------------------------------------------------------</span></span><br><span class="line"><span class="comment">// &lt;auto-generated&gt;</span></span><br><span class="line"><span class="comment">//     This code was generated by a tool.</span></span><br><span class="line"><span class="comment">//</span></span><br><span class="line"><span class="comment">//     Changes to this file may cause incorrect behavior and will be lost if</span></span><br><span class="line"><span class="comment">//     the code is regenerated.</span></span><br><span class="line"><span class="comment">// &lt;/auto-generated&gt;</span></span><br><span class="line"><span class="comment">//------------------------------------------------------------------------------</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// Generated from: proto/BattleMsg.proto</span></span><br><span class="line"><span class="keyword">namespace</span> <span class="title">proto.BattleMsg</span></span><br><span class="line">&#123;</span><br><span class="line">  [<span class="meta">global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@<span class="string">&quot;MsgMove&quot;</span>)</span>]</span><br><span class="line">  <span class="keyword">public</span> <span class="keyword">partial</span> <span class="keyword">class</span> <span class="title">MsgMove</span> : <span class="title">global</span>::<span class="title">ProtoBuf.IExtensible</span></span><br><span class="line">  &#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">MsgMove</span>()</span> &#123;&#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">private</span> <span class="built_in">int</span> _x = <span class="literal">default</span>(<span class="built_in">int</span>);</span><br><span class="line">    [<span class="meta">global::ProtoBuf.ProtoMember(1, IsRequired = false, Name=@<span class="string">&quot;x&quot;</span>, DataFormat = global::ProtoBuf.DataFormat.TwosComplement)</span>]</span><br><span class="line">    [<span class="meta">global::System.ComponentModel.DefaultValue(default(int))</span>]</span><br><span class="line">    <span class="keyword">public</span> <span class="built_in">int</span> x</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="keyword">get</span> &#123; <span class="keyword">return</span> _x; &#125;</span><br><span class="line">      <span class="keyword">set</span> &#123; _x = <span class="keyword">value</span>; &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">private</span> <span class="built_in">int</span> _y = <span class="literal">default</span>(<span class="built_in">int</span>);</span><br><span class="line">    [<span class="meta">global::ProtoBuf.ProtoMember(2, IsRequired = false, Name=@<span class="string">&quot;y&quot;</span>, DataFormat = global::ProtoBuf.DataFormat.TwosComplement)</span>]</span><br><span class="line">    [<span class="meta">global::System.ComponentModel.DefaultValue(default(int))</span>]</span><br><span class="line">    <span class="keyword">public</span> <span class="built_in">int</span> y</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="keyword">get</span> &#123; <span class="keyword">return</span> _y; &#125;</span><br><span class="line">      <span class="keyword">set</span> &#123; _y = <span class="keyword">value</span>; &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">private</span> <span class="built_in">int</span> _z = <span class="literal">default</span>(<span class="built_in">int</span>);</span><br><span class="line">    [<span class="meta">global::ProtoBuf.ProtoMember(3, IsRequired = false, Name=@<span class="string">&quot;z&quot;</span>, DataFormat = global::ProtoBuf.DataFormat.TwosComplement)</span>]</span><br><span class="line">    [<span class="meta">global::System.ComponentModel.DefaultValue(default(int))</span>]</span><br><span class="line">    <span class="keyword">public</span> <span class="built_in">int</span> z</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="keyword">get</span> &#123; <span class="keyword">return</span> _z; &#125;</span><br><span class="line">      <span class="keyword">set</span> &#123; _z = <span class="keyword">value</span>; &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">global</span>::ProtoBuf.IExtension extensionObject;</span><br><span class="line">    <span class="keyword">global</span>::ProtoBuf.IExtension <span class="keyword">global</span>::ProtoBuf.IExtensible.GetExtensionObject(<span class="built_in">bool</span> createIfMissing)</span><br><span class="line">      &#123; <span class="keyword">return</span> <span class="keyword">global</span>::ProtoBuf.Extensible.GetExtensionObject(<span class="keyword">ref</span> extensionObject, createIfMissing); &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  </span><br><span class="line">  [<span class="meta">global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@<span class="string">&quot;MsgAttack&quot;</span>)</span>]</span><br><span class="line">  <span class="keyword">public</span> <span class="keyword">partial</span> <span class="keyword">class</span> <span class="title">MsgAttack</span> : <span class="title">global</span>::<span class="title">ProtoBuf.IExtensible</span></span><br><span class="line">  &#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">MsgAttack</span>()</span> &#123;&#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">private</span> <span class="built_in">string</span> _desc = <span class="string">&quot;&quot;</span>;</span><br><span class="line">    [<span class="meta">global::ProtoBuf.ProtoMember(1, IsRequired = false, Name=@<span class="string">&quot;desc&quot;</span>, DataFormat = global::ProtoBuf.DataFormat.Default)</span>]</span><br><span class="line">    [<span class="meta">global::System.ComponentModel.DefaultValue(<span class="string">&quot;&quot;</span>)</span>]</span><br><span class="line">    <span class="keyword">public</span> <span class="built_in">string</span> desc</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="keyword">get</span> &#123; <span class="keyword">return</span> _desc; &#125;</span><br><span class="line">      <span class="keyword">set</span> &#123; _desc = <span class="keyword">value</span>; &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">global</span>::ProtoBuf.IExtension extensionObject;</span><br><span class="line">    <span class="keyword">global</span>::ProtoBuf.IExtension <span class="keyword">global</span>::ProtoBuf.IExtensible.GetExtensionObject(<span class="built_in">bool</span> createIfMissing)</span><br><span class="line">      &#123; <span class="keyword">return</span> <span class="keyword">global</span>::ProtoBuf.Extensible.GetExtensionObject(<span class="keyword">ref</span> extensionObject, createIfMissing); &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="具体使用"><a href="#具体使用" class="headerlink" title="具体使用"></a>具体使用</h2><figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">MsgMove msgMove = <span class="keyword">new</span> MsgMove();</span><br><span class="line">msgMove.x = <span class="number">214</span>;</span><br><span class="line"><span class="built_in">byte</span>[] bs = Encode(msgMove);</span><br><span class="line">Debug.Log(System.BitConverter.ToString(bs));</span><br><span class="line"><span class="comment">//解码</span></span><br><span class="line">ProtoBuf.IExtensible m = Decode(<span class="string">&quot;proto.BattleMsg.MsgMove&quot;</span>, bs, <span class="number">0</span>, bs.Length);</span><br><span class="line">MsgMove m2 = (MsgMove)m;</span><br><span class="line">Debug.Log(m2.x);</span><br></pre></td></tr></table></figure>
            <!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->
            <audio id="audio" loop="1" preload="auto" controls="controls" data-autoplay="false">
                <source type="audio/mpeg" src="/music/jucilang.mp3">
            </audio>
            
        </div>
        
    <div id='gitalk-container' class="comment link"
		data-enable='true'
        data-ae='true'
        data-ci='99f95a936c6fcdb1bd67'
        data-cs='c2d1bba3d6b7f9ade4f3de09a63925bd837c25ea'
        data-r='mrchenlearnspace.github.io'
        data-o='MrChenLearnSpace'
        data-a='MrChenLearnSpace'
        data-d='false'
    >查看评论</div>


    </div>
    
        <div class='side'>
			<ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%BD%91%E7%BB%9C%E6%A8%A1%E5%9E%8B"><span class="toc-number">1.</span> <span class="toc-text">网络模型</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#iocp%EF%BC%88Input-x2F-output-completion-port%EF%BC%89"><span class="toc-number">1.1.</span> <span class="toc-text">iocp（Input&#x2F;output completion port）</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%BC%BA%E7%82%B9"><span class="toc-number">1.1.1.</span> <span class="toc-text">缺点</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%8A%B6%E6%80%81%E6%A3%80%E6%B5%8BPoll"><span class="toc-number">1.2.</span> <span class="toc-text">状态检测Poll</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B3%A8%E6%84%8F"><span class="toc-number">1.2.1.</span> <span class="toc-text">注意</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%BC%BA%E7%82%B9-1"><span class="toc-number">1.2.2.</span> <span class="toc-text">缺点</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%A4%9A%E8%B7%AF%E5%A4%8D%E7%94%A8Select"><span class="toc-number">1.3.</span> <span class="toc-text">多路复用Select</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%BF%87%E7%A8%8B"><span class="toc-number">1.3.1.</span> <span class="toc-text">过程</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%80%82%E7%94%A8%E7%A9%BA%E9%97%B4"><span class="toc-number">1.3.2.</span> <span class="toc-text">适用空间</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E8%A7%A3%E5%86%B3%E7%B2%98%E5%8C%85%E9%97%AE%E9%A2%98%E7%9A%84%E6%96%B9%E6%B3%95"><span class="toc-number">2.</span> <span class="toc-text">解决粘包问题的方法</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%95%BF%E5%BA%A6%E4%BF%A1%E6%81%AF%E6%B3%95"><span class="toc-number">2.1.</span> <span class="toc-text">长度信息法</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9B%BA%E5%AE%9A%E9%95%BF%E5%BA%A6%E6%B3%95"><span class="toc-number">2.2.</span> <span class="toc-text">固定长度法</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BB%93%E6%9D%9F%E7%AC%A6%E5%8F%B7%E6%B3%95"><span class="toc-number">2.3.</span> <span class="toc-text">结束符号法</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%A4%A7%E7%AB%AF%E5%B0%8F%E7%AB%AF%E9%97%AE%E9%A2%98"><span class="toc-number">3.</span> <span class="toc-text">大端小端问题</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88"><span class="toc-number">3.1.</span> <span class="toc-text">解决方案</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#BytesArray"><span class="toc-number">4.</span> <span class="toc-text">BytesArray</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%BC%82%E6%AD%A5%E5%A4%84%E7%90%86"><span class="toc-number">5.</span> <span class="toc-text">异步处理</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%BC%82%E6%AD%A5%E8%BF%9E%E6%8E%A5"><span class="toc-number">5.1.</span> <span class="toc-text">异步连接</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%94%B9%E8%BF%9B"><span class="toc-number">5.1.1.</span> <span class="toc-text">改进</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%BC%82%E6%AD%A5%E5%8F%91%E9%80%81"><span class="toc-number">5.2.</span> <span class="toc-text">异步发送</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%94%B9%E8%BF%9B-1"><span class="toc-number">5.2.1.</span> <span class="toc-text">改进</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%BC%82%E6%AD%A5%E6%8E%A5%E6%94%B6"><span class="toc-number">5.3.</span> <span class="toc-text">异步接收</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%94%B9%E8%BF%9B-2"><span class="toc-number">5.3.1.</span> <span class="toc-text">改进</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#ProtoBuf"><span class="toc-number">6.</span> <span class="toc-text">ProtoBuf</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8"><span class="toc-number">6.1.</span> <span class="toc-text">使用</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%94%9F%E6%88%90%E4%BB%A3%E7%A0%81"><span class="toc-number">6.2.</span> <span class="toc-text">生成代码</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%85%B7%E4%BD%93%E4%BD%BF%E7%94%A8"><span class="toc-number">6.3.</span> <span class="toc-text">具体使用</span></a></li></ol></li></ol>	
        </div>
    
</div>


    </div>
</div>
</body>

<script src="//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js"></script>


<script src="//lib.baomitu.com/jquery/1.8.3/jquery.min.js"></script>
<script src="/blog/js/plugin.js"></script>
<script src="/blog/js/typed.js"></script>
<script src="/blog/js/diaspora.js"></script>


<link rel="stylesheet" href="/blog/photoswipe/photoswipe.css">
<link rel="stylesheet" href="/blog/photoswipe/default-skin/default-skin.css">


<script src="/blog/photoswipe/photoswipe.min.js"></script>
<script src="/blog/photoswipe/photoswipe-ui-default.min.js"></script>


<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>
    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">
        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>
        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">
            <div class="pswp__top-bar">
                <!--  Controls are self-explanatory. Order can be changed. -->
                <div class="pswp__counter"></div>
                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
                <button class="pswp__button pswp__button--share" title="Share"></button>
                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                      <div class="pswp__preloader__cut">
                        <div class="pswp__preloader__donut"></div>
                      </div>
                    </div>
                </div>
            </div>
            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div> 
            </div>
            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>
            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>
            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>
        </div>
    </div>
</div>



<script type="text/x-mathjax-config">
    MathJax.Hub.Config({"HTML-CSS": { preferredFont: "TeX", availableFonts: ["STIX","TeX"], linebreaks: { automatic:true }, EqnChunk: (MathJax.Hub.Browser.isMobile ? 10 : 50) },
        tex2jax: { inlineMath: [ ["$", "$"], ["\\(","\\)"] ], processEscapes: true, ignoreClass: "tex2jax_ignore|dno",skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']},
        TeX: {  noUndefined: { attributes: { mathcolor: "red", mathbackground: "#FFEEEE", mathsize: "90%" } }, Macros: { href: "{}" } },
        messageStyle: "none"
    });
</script>
<script type="text/x-mathjax-config">
    MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for(i=0; i < all.length; i += 1) {
            all[i].SourceElement().parentNode.className += ' has-jax';
        }
    });
</script>

<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>



<!-- Google Analytics -->
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-YMJ8CBH8F7"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-YMJ8CBH8F7');
</script>
<!-- End Google Analytics -->


</html>
